<template>
  <div class="setting-r-content">
    <div class="search-content">
      <Col class="panel search-panel" span="24">
      <Form :model="searchForm" :label-width="80" inline>
        <FormItem label="省份查询：">
          <Select v-model="searchForm.provinceId" clearable placeholder="省份查询" style="width: 200px">
            <Option v-for="(item,index) in provinceListOnSearch" :value="item.id" :key="index" :label="item.name" />
          </Select>
        </FormItem>
        <FormItem class="margin-l">
          <Button type="primary" @click="_queryThing" style="margin-right: 15px;">查询</Button>
          <Button type="primary" @click="_addNew" :disabled="userRole==='ROLE_DEMO'">新增</Button>
        </FormItem>
      </Form>
      </Col>
    </div>
    <div class="w1 setting-scroll__content">
      <Row class="setting-content__row">
        <Col class="panel table-panel" :span="24">
        <Table :columns="columns" :data="tableDatas" :loading="pageInfo.loading" border />
        </Col>
        <!-- 新增表单 -->
        <Modal v-model="dialogBox.add" width="30%;">
          <div slot="header">
            <span>新增地域</span>
            <Tooltip max-width="200" theme="light" content="一级地域下可以包括省份、直辖市；二级地域需要手动选择已存在省份后创建地级市。">
              <Icon type="ios-help-circle" size="14" />
            </Tooltip>
          </div>
          <Form :model="addForm" :label-width="100" :rules="rules" ref="addFormRef">
            <FormItem prop="region" label="地域级别：">
              <Select v-model="addForm.region" filterable placeholder="请选择地域级别" style="width: 200px" @on-change="onRegionLevelChange">
                <Option v-for="(item,index) in regionLevel" :value="item.level" :key="index" :label="item.name" />
              </Select>
            </FormItem>
            <FormItem v-if="addForm.region===3" label="所属省份" prop="provinceId">
              <Select v-model="addForm.provinceId" style="width: 200px" clearable @on-change="onProvinceChange">
                <Option v-for="item in provinceList" :value="item.id" :key="item.id" :label="item.name" />
              </Select>
            </FormItem>
            <FormItem label="地域名称：" prop="name">
              <Select v-model="addForm.name" style="width: 200px" clearable @on-change="onNameChange">
                <Option v-for="(item,index) in regionList" :value="item.name" :key="index" :label="item.name" />
              </Select>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button @click="dialogBox.add=false">取消</Button>
            <Button type="primary" @click="submitAddNew" :loading="dialogBox.btnloading">确定</Button>
          </div>
        </Modal>
      </Row>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex"
import {
  getRegionByParams,
  getRegionAll,
  deleteRegion,
  postRegion,
  postSecondArea,
  deleteSecondArea
} from "@/api"
import { generatedColumns, generatedRules, regionLevel } from "./utils"
import { idMapProvince, idMapCity } from "@/utils/mapConfig"
export default {
  mounted() {
    this.getProvinceList()
    this.getRegionOnSearch()
  },
  computed: {
    ...mapState({
      userRole: state => state.userInfo.rname
    })
  },
  data() {
    return {
      searchForm: {
        provinceId: ""
      },
      regionLevel: [...regionLevel],
      provinceList: [],
      regionList: [],
      provinceListOnSearch: [],

      cityList: [],
      addForm: {
        region: "",
        provinceId: "",
        name: "",
        sysCode: ""
      },

      dialogBox: {
        add: false,
        btnloading: false
      },
      pageInfo: {
        loading: false,
        total: 0,
        page: 1
      },
      tableDatas: [],
      columns: generatedColumns(this),
      rules: generatedRules()
    }
  },
  methods: {
    handelOnSearchChange(value) {
      if (String(value) === "00" || value === 0 || !isNaN(value)) {
        return false
      }
    },
    onRegionLevelChange(value) {
      const vm = this
      vm.addForm.name = null
      // value === 3 二级地域
      if (value === 3) {
        vm.regionList = []
        vm.addForm.provinceId = ""
        vm.addForm.name = ""
        vm.getRegionByParams_()
      } else {
        vm.regionList = [...idMapProvince]
      }
    },

    onNameChange(name) {
      if (name) {
        this.addForm.sysCode = this.regionList.find(t => t.name === name).code
      }
    },

    // 省份change事件
    onProvinceChange(id) {
      if (!id) return false
      let name = this.provinceList.find(t => t.id === id).name
      let code = idMapProvince.find(t => t.name === name).code
      if (!!id) this.addForm.name = ""
      this.regionList = idMapCity[code]
    },

    // 获取搜索条件中的省份列表
    getRegionOnSearch() {
      getRegionByParams({
        type: 2
      }).then(res => {
        if (res.code === 200) {
          this.provinceListOnSearch = res.data
        }
      })
    },

    // 新建区域时获取省份列表
    getRegionByParams_() {
      const specialCity = ["北京市", "天津市", "重庆市", "上海市"]
      getRegionByParams({ type: 2 }).then(res => {
        if (res.code === 200) {
          let result = res.data.filter(t => {
            if (!specialCity.includes(t.name)) {
              return t
            }
          })
          this.provinceList = result
        }
      })
    },

    _queryThing() {
      let vm = this
      vm.pageInfo.page = 1
      this.getProvinceList()
    },

    _addNew() {
      this.dialogBox.add = true
      this.$nextTick(_ => {
        this.$refs.addFormRef.resetFields()
      })
    },

    // 新增一级地域
    firstaryArea() {
      const vm = this,
        params = {
          name: this.addForm.name,
          type: this.addForm.region,
          sysCode: this.addForm.sysCode
        }
      return new Promise((resolve, reject) => {
        postRegion(params).then(res => {
          if (res.code === 200) {
            resolve()
          } else {
            reject(res.message)
          }
        })
      })
    },

    // 新增二级地域
    secondaryArea() {
      const vm = this,
        params = {
          provinceId: this.addForm.provinceId,
          name: this.addForm.name,
          sysCode: this.addForm.sysCode
        }
      return new Promise((resolve, reject) => {
        postSecondArea(params).then(res => {
          if (res.code === 200) {
            resolve()
          } else {
            reject(res.message)
          }
        })
      })
    },

    submitAddNew() {
      const { region } = this.addForm
      const provinceId = this.addForm.provinceId
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          this.dialogBox.btnloading = true
          if (region === 3) {
            this.secondaryArea()
              .then(() => {
                this.getProvinceList()
                this.getRegionOnSearch()
                this.dialogBox.add = false
                this.dialogBox.btnloading = false
              })
              .catch(message => {
                this.$Message.error(message)
                this.dialogBox.btnloading = false
              })
          } else {
            this.firstaryArea()
              .then(() => {
                this.getProvinceList()
                this.getRegionOnSearch()
                this.dialogBox.add = false
                this.dialogBox.btnloading = false
              })
              .catch(message => {
                this.$Message.error(message)
                this.dialogBox.btnloading = false
              })
          }
        }
      })
    },

    // 获取表格数据（获取所有地域）
    getProvinceList() {
      const params = {
        ...this.searchForm
      }
      this.pageInfo.loading = true
      getRegionAll(params).then(res => {
        if (res.code == 200) {
          this.tableDatas = res.data
          this.pageInfo.loading = false
        } else {
          this.pageInfo.loading = false
        }
      })
    },

    handleDelete(row) {
      const { type, id } = row
      if (type === 1) {
        this.deleteFristArea(id)
      } else if (type === 2) {
        this.deleteSecondArea(id)
      }
    },

    // 删除一级地域
    deleteFristArea(id) {
      deleteRegion(id).then(res => {
        if (res.code === 200) {
          this.$Message.success("操作成功")
          this.getProvinceList()
        } else {
          this.$Message.error(res.message)
        }
      })
    },

    // 删除二级地域
    deleteSecondArea(id) {
      deleteSecondArea(id).then(res => {
        if (res.code === 200) {
          this.$Message.success("操作成功")
          this.getProvinceList()
        } else {
          this.$Message.error(res.message)
        }
      })
    }
  }
}
</script>
